<template>
  <view class="app-container">
    <image class="background" src="/static/images/background.png" mode="aspectFill"></image>

    <view class="bar-box" :style="{ marginTop: titleMargin + 'px' }">
      <image class="back" src="/static/images/back.png" @click="back"></image>
      <view class="title">消息</view>
    </view>

    <view class="list">
      <view class="box" @click="goChat(item.to_user_id, item.username, item.avatar, index)" v-for="(item, index) in list" :key="index">
        <view class="avatar-box">
          <image class="avatar" :src="item.avatar" mode="aspectFill"></image>
          <view class="unread" v-if="item.unread_num > 0">{{ item.unread_num }}</view>
        </view>
        <view class="msg-box">
          <view class="top">
            <view class="nickname">{{ item.username }}</view>
            <view class="time">{{ item.new_create_time }}</view>
          </view>
          <view class="bottom">
            <view class="text">{{ item.new_content }}</view>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import {sendTextMessage, onMessage, offMessage, initWebSocket} from '@/utils/function/ws.js';

export default {
  data() {
    return {
      socketTask: null, // WebSocket实例
      title: '',
      titleMargin: 0, // 动态顶部间距
      list: [],
      page: 1,
      pagesize: 10,
    };
  },

  created() {
    this.setDynamicMargin(); // 设置动态间距
  },

  onShow: function (){
    uni.hideShareMenu();
  },

  onLoad: function () {
    this.chatUserList();

    // 订阅 WebSocket 消息
    this.messageHandler = (data) => {
      console.log("列表收到消息:", data);
      if (data.type === 'receive') {
        var user_id = data.user_id,
          content = data.content;

        this.updateMessageList(this.list, user_id, content, '刚刚')
      }
    };
    onMessage(this.messageHandler);
  },

  onUnload() {
    if (this.socketTask) {
      this.socketTask.close();
    }
  },

  methods: {
    back: function () {
      uni.navigateBack();
    },

    updateMessageList: function (list, user_id, content, create_time) {
      // 查找索引
      let index = list.findIndex(item => item.to_user_id === user_id);

      if (index !== -1) {
        // 取出匹配的项
        let matchedItem = list[index];

        // 更新数据
        matchedItem.new_content = content;
        matchedItem.new_create_time = create_time;

        var pages = getCurrentPages();
        var currentPage = pages[pages.length - 1];
        if(currentPage.route == 'pages/chat_list/chat_list') matchedItem.unread_num += 1;

        // 移动到数组最前面
        list.splice(index, 1);  // 删除原位置
        list.unshift(matchedItem); // 插入到最前面
        this.list = list;
      }else{
        this.chatUserList();
      }
    },

    setDynamicMargin() {
      const windowInfo = uni.getWindowInfo();
      this.titleMargin = windowInfo.statusBarHeight + 10; // 直接使用状态栏高度
    },

    goChat: function (to_user_id, username, avatar, index) {
      var user_id = uni.getStorageSync('user_id');
      this.$http.post('/index/Chat/checkCanChat', {user_id, to_user_id}).then(res => {
        if(res.data.result == 1){
          uni.navigateTo({
            url: '/pages/chat/chat?to_user_id=' + to_user_id + '&username=' + username + '&avatar=' + avatar + '&index=' + index
          })
        }else{
          uni.navigateTo({
            url: '/pages/tip/tip?type=2'
          })
        }
      })
    },

    chatUserList: function (incPage = 0) {
      var page = incPage ? incPage : this.page;

      uni.showLoading({
        title: '数据加载中...',
        mask: true
      })

      this.$http.post('/index/Chat/chatUserList', {
        user_id: uni.getStorageSync('user_id'),
        page: page,
        pagesize: this.pagesize
      }).then((res) => {
        if (res.data.result == 1) {
          if (page == 1) {
            this.list = res.data.data;
          } else {
            // 加载更多
            var list = this.list;

            for (var i = 0; i < res.data.data.length; i++) {
              list.push(res.data.data[i]);
            }

            this.list = list;
            this.page = page;
          }

          setTimeout(() => {
            uni.hideLoading();
          }, 500)
        } else {
          uni.hideLoading();
          if (page == 1) this.list = [];
        }
      })
    }
  },
}
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 10rpx;

  .list {
    display: flex;
    flex-direction: column;
    width: calc(100% - 40px);

    .box {
      display: flex;
      justify-content: space-between;
      width: 100%;
      padding: 40rpx 0;
      border-bottom: 2rpx solid #ccc;

      .avatar-box {
        position: relative;

        .avatar {
          width: 120rpx;
          height: 120rpx;
          border-radius: 20rpx;
          margin-right: 20rpx;
          flex-shrink: 0;
        }

        .unread {
          position: absolute;
          top: -16rpx;
          right: 4rpx;
          background: red;
          color: #fff;
          font-size: 20rpx;
          width: 40rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          border-radius: 50%;
        }
      }


      .msg-box {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;

        .top {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .nickname {
            font-size: 36rpx;
          }
        }

        .bottom {
          color: $uni-text-color-placeholder;

          .text {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style>
